package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.myapplication.adapter.FoodInfo;

import java.util.List;

public class FoodAdapter extends BaseAdapter{
    //①添加构造方法
    //参数1 上下文 参数2：布局资源  参数3：列表实体类 范类数据

    private Context context;
    private int resourceId;
    private List<FoodInfo> data; //数据载体

    public FoodAdapter(Context context, int resourceId, List<FoodInfo> data){
        super();
        this.context = context;
        this.resourceId = resourceId;
        this.data = data;
    }


    @Override
    //获取到列表的长度
    public int getCount() {
        return data.size();
    }

    @Override
    //获取到类别对应的Item
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    //位置
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        //实例化实体类
        FoodInfo foodInfo = (FoodInfo) getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView == null){
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(context).inflate(resourceId,parent,false);
            viewHolder.ivFood = view.findViewById(R.id.iv_food_image);
            viewHolder.tvTitle = view.findViewById(R.id.tv_food_name);
            viewHolder.tvContent = view.findViewById(R.id.tv_food_context);
            view.setTag(viewHolder);
        } else{
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.ivFood.setImageResource(foodInfo.getIcon());
        viewHolder.tvTitle.setText(foodInfo.getTitle());
        viewHolder.tvContent.setText(foodInfo.getContent());

        return view;
    }
   public class ViewHolder{
       ImageView ivFood;
       TextView tvTitle;
       TextView tvContent;
    }
}
